<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

/**
 * NGMenu component helper.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_ngmenu
 * @since		1.6
 */
class NGMenuHelper
{
	
	/**
	 * Checks if the given font family is supplied by google web fonts.
	 *
	 * @param	string	Font Family Name
	 *
	 * @return	boolean, TRUE on success, and otherwise FALSE
	 * @since	1.7.0
	 */
	public static function isGoogleFont($font_name=null)
	{
		if (!$font_name) return false;
		$font_name = str_replace('+', ' ', $font_name);
		$font_name = explode('|', $font_name);
		
		$database =& JFactory::getDBO();
		$select = $database->getQuery(true);
		$select->select('*');
		$select->from('#__ngmenu_fonts');
		$select->where("name='".$font_name[0]."'");
		$database->setQuery($select);
		$database->query();
		if($database->getNumRows()){
			return true;
		}else{
			return false;
		}
	}

	public static function prepareFontFamily($font_family){
		
		$font_family = str_replace('+', ' ', $font_family);
		$font_family = explode('|', $font_family); //der zweite teil des arrays ist das subset
		if(self::isGoogleFont($font_family[0])){
			return "'".$font_family[0]."',arial,serif";
		}else{
			return $font_family[0];
		}
	}

	public static function prepareFontWeight($font_weight, $ngmenu=false){
		if (preg_match("|(\d+)|", $font_weight, $matches)){ //wenn eine zahl in $font_weight enthalten ist, dann handelt es sich um Google Web Font mit font-weight und font-style
			$weight = 'font-weight:'.$matches[0].';';
			$font_style = str_replace($matches[0], '', $font_weight);
			$style = (empty($font_style)) ? 'font-style:normal;' : 'font-style:'.$font_style.';';
			if($ngmenu){
				$font_style = (empty($font_style)) ? 'normal' : $font_style;
				return $font_style.' '.$matches[0];
//				return $matches[0].' '.$font_style;
			}else{
				return $weight.$style;
			}
		}else{
			if($ngmenu){
				return $font_weight;
			}else{
				return 'font-weight:'.$font_weight.';';
			}
		}
	}
	
	public static function getGoogleFontParms($font_family, $font_weight){
		
		$font_parm = ''; $i = 0; $gfonts = $subsets = array();
		
		if(self::isGoogleFont($font_family)){
			$gfonts[$font_family][] = $font_weight;
		}

		if(count($gfonts)){
			foreach($gfonts as $font_family => $weight_values){
				$font_delimiter = ($i==0) ? '' : '|';
				$font_family = explode('|', $font_family);
				$font_parm .= $font_delimiter.$font_family[0].':'.implode(',', $weight_values);
				$subsets[] = $font_family[1];
				$i+=1;
			}
			if(!empty($font_parm)){
				$subsets = array_unique($subsets);
				$font_parm .= '&subset='.implode(',', $subsets);
			}
		}
		return $font_parm;
	}
}
